//
//  PowerCircleView.swift
//  SCA
//
//  Created by tjun on 2025/9/5.
//

import UIKit
import SnapKit

struct PowerSegment {
    let value: CGFloat
    let color: UIColor
    let title: String
    let model: PowerModel?
    
    init(value: CGFloat, color: UIColor, title: String, model: PowerModel? = nil) {
        self.value = value
        self.color = color
        self.title = title
        self.model = model
    }
}

class PowerCircleView: UIView {
    

    var segments: [PowerSegment] = [] {
        didSet { setNeedsDisplay(); }
    }
    
    var powerInfo: PowerInfo? {
        didSet {
            guard let powerInfo = powerInfo,
                  let mintingModel = powerInfo.cat[.minting],
                  let matrixModel = powerInfo.cat[.matrix],
                  let differentialModel = powerInfo.cat[.differential],
                  let peerModel = powerInfo.cat[.peer] else { return }
            
            setCenterText(top: "算力".localizedString, value: powerInfo.total, unit: "G")
            
            segments = [
                PowerSegment(value: CGFloat((mintingModel.percent as NSString).floatValue), color: UIColor.hexStringColor(hexString: mintingModel.color), title: mintingModel.title, model: mintingModel),
                
                PowerSegment(value: CGFloat((matrixModel.percent as NSString).floatValue), color: UIColor.hexStringColor(hexString: matrixModel.color), title: matrixModel.title, model: matrixModel),
                
                PowerSegment(value: CGFloat((differentialModel.percent as NSString).floatValue), color: UIColor.hexStringColor(hexString: differentialModel.color), title: differentialModel.title, model: differentialModel),
                PowerSegment(value: CGFloat((peerModel.percent as NSString).floatValue), color: UIColor.hexStringColor(hexString: peerModel.color), title: peerModel.title, model: peerModel),
            ]
        }
    }
    
    let backgroundView = UIView()
    private let centerLabel = UILabel()
    private let lineWidth: CGFloat = 12
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        setupCenterLabel()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupCenterLabel() {
        
        backgroundView.addTo(self)
        backgroundView.backgroundColor = .white
        
        centerLabel.numberOfLines = 0
        centerLabel.textAlignment = .center
        
        addSubview(centerLabel)
        
        centerLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }

    override func draw(_ rect: CGRect) {
        guard !segments.isEmpty else { return }
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        
        let radius = min(rect.width, rect.height) / 2 - lineWidth / 2
        var gapAngle: CGFloat = .pi / 180 * 2 // 默认每段间隔 2 度
        
        let total = segments.reduce(0) { $0 + $1.value }
        let nonZeroSegments = segments.filter { $0.value > 0 }
        
        if nonZeroSegments.count <= 1 {
            gapAngle = 0
        }
        
        var startAngle: CGFloat = -.pi / 2
        
        for segment in segments {
            let angle = (segment.value / total) * 2 * .pi
            let drawStart = startAngle + gapAngle / 2
            let drawEnd = startAngle + angle - gapAngle / 2
            
            if drawEnd > drawStart {
                ctx.setStrokeColor(segment.color.cgColor)
                ctx.setLineWidth(lineWidth)
                ctx.setLineCap(.butt)
                
                ctx.addArc(center: CGPoint(x: rect.midX, y: rect.midY),
                           radius: radius,
                           startAngle: drawStart,
                           endAngle: drawEnd,
                           clockwise: false)
                ctx.strokePath()
            }
            
            startAngle += angle
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let backgroundViewW = min(frame.width, frame.height) - (lineWidth + 10) * 2
        backgroundView.frame = CGRectMake(lineWidth + 10, (frame.height - backgroundViewW) * 0.5, backgroundViewW, backgroundViewW)
        backgroundView.addCorner(radius: backgroundViewW * 0.5)
    }
    
    func setCenterText(top: String, value: String, unit: String) {
        let text = NSMutableAttributedString()
        let topAttr = NSAttributedString(string: "\(top)\n", attributes: [
            .font: UIFont.systemFont(ofSize: 12),
            .foregroundColor: UIColor.black
        ])
        text.append(topAttr)
        let valueAttr = NSAttributedString(string: "\(value)\n", attributes: [
            .font: UIFont.systemFont(ofSize: 20, weight: .semibold),
            .foregroundColor: UIColor.black
        ])
        text.append(valueAttr)
        let unitAttr = NSAttributedString(string: unit, attributes: [
            .font: UIFont.systemFont(ofSize: 20, weight: .semibold),
            .foregroundColor: UIColor.black
        ])
        text.append(unitAttr)
        
        centerLabel.attributedText = text
    }
}


//import UIKit
//import SnapKit
//
//struct PowerSegment {
//    let value: CGFloat   // 可以是百分比（如 0.3）或任意权重（归一化会自动完成）
//    let color: UIColor
//    let title: String
//}
//
//class PowerCircleView: UIView {
//
//    // MARK: - public
//    var segments: [PowerSegment] = [] {
//        didSet {
//            setupLegend()
//            needsAnimateSegments = false
//            setNeedsLayout()
//        }
//    }
//    var animateOnUpdate: Bool = true
//    var totalAnimationDuration: CFTimeInterval = 1
//    var gapDegrees: CGFloat = 2
//
//    // MARK: - subviews & layers
//    private let backgroundView = UIView()
//    private let centerLabel = UILabel()
//    private let legendStack = UIStackView()
//    private let lineWidth: CGFloat = 12
//
//    private let arcContainerLayer = CALayer()
//    private var arcLayers: [CAShapeLayer] = []
//
//    // internal flag
//    private var needsAnimateSegments: Bool = false
//
//    // MARK: - init
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        backgroundColor = .clear
//        layer.addSublayer(arcContainerLayer) // arcs live here (under subviews)
//        setupCenterLabel()
//        setupLegendStack()
//    }
//
//    required init?(coder: NSCoder) {
//        super.init(coder: coder)
//        layer.addSublayer(arcContainerLayer)
//        setupCenterLabel()
//        setupLegendStack()
//    }
//
//    // MARK: - UI Setup
//    private func setupCenterLabel() {
//        backgroundView.backgroundColor = UIColor(white: 0.06, alpha: 0.9) // 你可改颜色
//        addSubview(backgroundView)
//
//        centerLabel.numberOfLines = 0
//        centerLabel.textAlignment = .center
//        centerLabel.font = UIFont.boldSystemFont(ofSize: 22)
//        centerLabel.textColor = .white
//        backgroundView.addSubview(centerLabel)
//
//        centerLabel.snp.makeConstraints { make in
//            make.center.equalToSuperview()
//            make.width.lessThanOrEqualTo(backgroundView.snp.width).offset(-20)
//        }
//    }
//
//    private func setupLegendStack() {
//        legendStack.axis = .vertical
//        legendStack.spacing = 8
//        legendStack.alignment = .leading
//        addSubview(legendStack)
//
//        // 注意：原来你是把 legend 放到 view 右侧的外面，这里保留同样位置（根据布局需要可调整）
//        legendStack.snp.makeConstraints { make in
//            make.leading.equalTo(self.snp.trailing).offset(30)
//            make.centerY.equalToSuperview()
//        }
//    }
//
//    private func setupLegend() {
//        legendStack.arrangedSubviews.forEach { $0.removeFromSuperview() }
//        for segment in segments {
//            let item = legendItem(color: segment.color, title: segment.title)
//            legendStack.addArrangedSubview(item)
//        }
//    }
//
//    private func legendItem(color: UIColor, title: String) -> UIView {
//        let stack = UIStackView()
//        stack.axis = .horizontal
//        stack.spacing = 6
//        stack.alignment = .center
//
//        let dot = UIView()
//        dot.backgroundColor = color
//        dot.layer.cornerRadius = 5
//        dot.snp.makeConstraints { make in
//            make.width.height.equalTo(10)
//        }
//
//        let label = UILabel()
//        label.text = title
//        label.font = UIFont.systemFont(ofSize: 14)
//        label.textColor = color
//        label.numberOfLines = 0
//        label.setContentCompressionResistancePriority(.required, for: .vertical)
//
//        stack.addArrangedSubview(dot)
//        stack.addArrangedSubview(label)
//        stack.snp.makeConstraints { make in
//            make.height.greaterThanOrEqualTo(20)
//        }
//        return stack
//    }
//
//    // MARK: - layout & drawing
//    override func layoutSubviews() {
//        super.layoutSubviews()
//
//        // layout background circle in center
//        let backgroundViewW = min(frame.width, frame.height) - (lineWidth + 10) * 2
//        backgroundView.frame = CGRect(
//            x: (frame.width - backgroundViewW) / 2,
//            y: (frame.height - backgroundViewW) / 2,
//            width: backgroundViewW,
//            height: backgroundViewW
//        )
//        backgroundView.layer.cornerRadius = backgroundViewW / 2
//        backgroundView.clipsToBounds = true
//
//        // ensure arc container covers full view
//        arcContainerLayer.frame = bounds
//
//        // 如果需要动画或刷新，执行重建
//        if needsAnimateSegments {
//            reloadArcLayers(animated: animateOnUpdate)
//            needsAnimateSegments = false
//        }
//    }
//
//    // MARK: - arc layer creation + animation
//    private func reloadArcLayers(animated: Bool) {
//        // clear old arc layers
//        arcLayers.forEach { $0.removeFromSuperlayer() }
//        arcLayers.removeAll()
//
//        guard !segments.isEmpty else { return }
//
//        let total = segments.reduce(CGFloat(0)) { $0 + $1.value }
//        guard total > 0 else { return }
//
//        let center = CGPoint(x: bounds.midX, y: bounds.midY)
//        let radius = min(bounds.width, bounds.height) / 2 - lineWidth / 2
//        let gapAngle = gapDegrees * .pi / 180
//
//        var startAngle: CGFloat = -.pi / 2
//
//        // total animation duration distributed proportionally
//        let totalDuration = animated ? totalAnimationDuration : 0
//        var cumulativeDelay: CFTimeInterval = 0
//
//        for segment in segments {
//            let angle = (segment.value / total) * 2 * .pi
//            if angle <= 0.001 { // negligible, skip
//                startAngle += angle
//                continue
//            }
//
//            // shrink the drawable arc by gapAngle (split gap half on each side)
//            let drawableAngle = max(0, angle - gapAngle)
//            let a0 = startAngle + gapAngle / 2
//            let a1 = a0 + drawableAngle
//
//            let path = UIBezierPath(arcCenter: center,
//                                    radius: radius,
//                                    startAngle: a0,
//                                    endAngle: a1,
//                                    clockwise: true)
//
//            let shape = CAShapeLayer()
//            shape.path = path.cgPath
//            shape.strokeColor = segment.color.cgColor
//            shape.fillColor = UIColor.clear.cgColor
//            shape.lineWidth = lineWidth
//            shape.lineCap = .butt
//            shape.strokeEnd = animated ? 0 : 1
//
//            arcContainerLayer.addSublayer(shape)
//            arcLayers.append(shape)
//
//            if animated {
//                // per-segment duration proportional to its angle
//                let segDuration = totalDuration * CFTimeInterval(angle / (2 * .pi))
//                let animation = CABasicAnimation(keyPath: "strokeEnd")
//                animation.fromValue = 0
//                animation.toValue = 1
//                animation.duration = max(0.01, segDuration) // avoid zero-duration
//                animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
//                // schedule sequentially using beginTime
//                animation.beginTime = CACurrentMediaTime() + cumulativeDelay
//                animation.fillMode = .forwards
//                animation.isRemovedOnCompletion = false
//
//                shape.add(animation, forKey: "strokeEndAnim")
//                // set model layer final value so UI stays correct after animation ends
//                DispatchQueue.main.asyncAfter(deadline: .now() + cumulativeDelay + segDuration) {
//                    shape.strokeEnd = 1
//                    // optionally remove the animation key to clean up
//                    shape.removeAnimation(forKey: "strokeEndAnim")
//                }
//
//                cumulativeDelay += segDuration
//            }
//
//            startAngle += angle
//        }
//    }
//
//    // MARK: - center text
//    func setCenterText(top: String, value: String, unit: String) {
//        let text = NSMutableAttributedString()
//        let topAttr = NSAttributedString(string: "\(top)\n", attributes: [
//            .font: UIFont.systemFont(ofSize: 16),
//            .foregroundColor: UIColor.gray
//        ])
//        text.append(topAttr)
//        let valueAttr = NSAttributedString(string: "\(value)\n", attributes: [
//            .font: UIFont.boldSystemFont(ofSize: 28),
//            .foregroundColor: UIColor.white
//        ])
//        text.append(valueAttr)
//        let unitAttr = NSAttributedString(string: unit, attributes: [
//            .font: UIFont.systemFont(ofSize: 16),
//            .foregroundColor: UIColor.gray
//        ])
//        text.append(unitAttr)
//
//        centerLabel.attributedText = text
//    }
//}
